﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using Infragistics.Win.UltraWinGrid;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace AutoParkingManagement
{
    public partial class CardList : Form
    {
        #region Private members
        private AddDeleteCard frmAddDeleteCard;
        private UltraGridRow _selectedRow;

        /// <summary>
        /// Reset search conditions
        /// </summary>
        private void Reset()
        {
            cboStatus.SelectedIndex = -1;
            cboCardType.SelectedIndex = -1;
            txtCardID.Text = String.Empty;            
        }

        /// <summary>
        /// Search data
        /// </summary>
        private void Search(object cardTypeID, object cardID, object cardStatus)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT c.CardTypeID, CardID, VIP, FromDate, ToDate, Active, ");
            sb.Append("CASE WHEN Active =1 THEN N'Kích hoạt' ELSE N'Vô hiệu' END AS Status ");
            sb.Append("FROM Card c LEFT JOIN CardType t ON c.CardTypeID = t.CardTypeID ");
            sb.Append("WHERE (@CardTypeID IS NULL OR c.CardTypeID=@CardTypeID) ");
            sb.Append("AND (@CardID IS NULL OR CardID LIKE ('%' + @CardID + '%')) ");
            sb.Append("AND (@CardStatus IS NULL OR Active=@CardStatus) ");
            SqlParameter[] parms = new SqlParameter[3];
            parms[0] = new SqlParameter();
            parms[0].ParameterName = "@CardTypeID";
            parms[0].SqlDbType = SqlDbType.UniqueIdentifier;
            parms[0].Value = cardTypeID;                       

            parms[1] = new SqlParameter();
            parms[1].ParameterName = "@CardID";
            parms[1].SqlDbType = SqlDbType.NVarChar;
            parms[1].Size = 50;
            parms[1].Value = Common.DBNullValue(txtCardID.Text);

            parms[2] = new SqlParameter();
            parms[2].ParameterName = "@CardStatus";
            parms[2].SqlDbType = SqlDbType.Bit;
            parms[2].Value = cardStatus;
            
            dgResult.DataSource = SqlHelper.ExecuteDataTable(CommandType.Text, sb.ToString(), parms);
        }

        private void frmEditCard_UpdateCard(UltraGridRow row)
        {
            row.Update();
        }

        private void DisplayLabelError(string content)
        {            
            if (frmAddDeleteCard != null)
            {
                frmAddDeleteCard.LabelError.Text = content;
            }
        }

        private void DeleteCard(string cardID)
        {            
            DisplayLabelError(String.Empty);
            
            if (String.IsNullOrEmpty(cardID))
            {
                return;
            }
            if (!CardExisted(cardID))
            {                
                DisplayLabelError("Thẻ này đã xóa.");
                return;
            }

            if (CardInUsed(cardID))
            {
                MessageBox.Show("Thẻ này đang được sử dụng.\nKhông thể xóa được.");
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("DELETE FROM Card ");            
            sb.Append("WHERE CardID = @CardID");
            SqlParameter parm = new SqlParameter();
            parm.ParameterName = "@CardID";
            parm.SqlDbType = SqlDbType.NVarChar;
            parm.Size = 50;
            parm.Value = cardID;
            SqlHelper.ExecuteNonQuery(CommandType.Text, sb.ToString(), parm);
            foreach (UltraGridRow row in dgResult.Rows)
            {
                if (row.Cells["CardID"].Value.ToString().Equals(cardID))
                {
                    row.Selected = true;
                    dgResult.DeleteSelectedRows(false);                    
                    DisplayLabelError("Thẻ này đã xóa.");
                    return;
                }
            }            
        }

        private bool CardExisted(string cardID)
        {
            ///////////////////////////////////////
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT Count(CardID) FROM Card ");
            sb.Append("WHERE CardID = @CardID ");

            SqlParameter parm = new SqlParameter("@CardID", SqlDbType.NVarChar, 50);
            parm.Value = cardID;
            object objEntry = SqlHelper.ExecuteScalar(CommandType.Text, sb.ToString(), parm);
            return ((int)objEntry > 0);
        }

        private bool CardInUsed(string cardID)
        {
            ///////////////////////////////////////
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT Count(CardID) FROM EntryExit ");
            sb.Append("WHERE CardID = @CardID ");

            SqlParameter parm = new SqlParameter("@CardID", SqlDbType.NVarChar, 50);
            parm.Value = cardID;
            object objEntry = SqlHelper.ExecuteScalar(CommandType.Text, sb.ToString(), parm);
            return ((int)objEntry > 0);
        }

        private bool AddCard(Guid cardTypeID, string cardID, bool VIP)
        {
            if (String.IsNullOrEmpty(cardID))
            {                
                return false;
            }
            if (CardExisted(cardID))
            {                
                frmAddDeleteCard.LabelError.Text = "Thẻ này đã nạp rồi.";               
                return false;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO Card (CardTypeID, CardID, VIP, Active, LastUser) ");
            sb.Append("VALUES (@CardTypeID, @CardID, @VIP, @Active, @LastUser) ");            
            SqlParameter[] parms = new SqlParameter[5];
            parms[0] = new SqlParameter("@CardTypeID", SqlDbType.UniqueIdentifier);            
            parms[0].Value = cardTypeID;

            parms[1] = new SqlParameter("@CardID", SqlDbType.NVarChar,50);            
            parms[1].Value = Common.DBNullValue(cardID);

            parms[2] = new SqlParameter("@VIP", SqlDbType.Bit);
            parms[2].Value = VIP;

            parms[3] = new SqlParameter("@Active", SqlDbType.Bit);            
            parms[3].Value = true;

            parms[4] = new SqlParameter("@LastUser", SqlDbType.UniqueIdentifier);
            parms[4].Value = MainParent.EmpWorking.Employee.Id;
            SqlHelper.ExecuteNonQuery(CommandType.Text, sb.ToString(), parms);            
            return true;
        }
                
        /// <summary>
        /// Add/remove card
        /// </summary>
        /// <param name="cardTypeID">card type ID</param>
        /// <param name="cardID">card ID</param>
        private void frm_CardAddedRemoved(Guid cardTypeID, string cardID, bool VIP)
        {
            DataTable dtSource;
            if (dgResult.DataSource == null)
            {
                dtSource = new DataTable();
                dtSource.Columns.Add("CardTypeID", typeof(Guid));
                dtSource.Columns.Add("CardID", typeof(string));
                dtSource.Columns.Add("VIP", typeof(bool));
                dtSource.Columns.Add("FromDate", typeof(DateTime));
                dtSource.Columns.Add("ToDate", typeof(DateTime));
                dtSource.Columns.Add("Active", typeof(bool));
                dtSource.Columns.Add("Status", typeof(string));
            }
            else
            {
                dtSource = (DataTable)dgResult.DataSource;
            }

            if (cardTypeID == Guid.Empty) //delete card
            {
                if (dtSource.Rows.Count == 0)
                {
                    frmAddDeleteCard.StopReadCard();
                    return;
                }
                DeleteCard(cardID);
            }
            else
            {
                if (!AddCard(cardTypeID, cardID,VIP)) return;                
                /////////////////////////////
                DataRow row = dtSource.NewRow();
                row["CardTypeID"] = cardTypeID;
                row["CardID"] = cardID;
                row["VIP"] = VIP;
                row["FromDate"] = DBNull.Value;
                row["ToDate"] = DBNull.Value;
                row["Status"] = "Vô hiệu";
                dtSource.Rows.InsertAt(row, 0);
                dtSource.AcceptChanges();                                
                dgResult.DataSource = dtSource;
                dgResult.DataBind();
                dgResult.Refresh();
                if (dgResult.Rows.Count > 0)
                {
                    dgResult.Rows[0].Cells[0].Activate();
                }
                frmAddDeleteCard.LabelError.Text = "Thẻ đã được thêm.";
            }            
        }
        #endregion

        #region Properties
        /// <summary>
        /// Selected row from Data grid view
        /// </summary>
        public UltraGridRow SelectedRow
        {
            get
            {
                return _selectedRow;
            }
        }        
        #endregion

        #region Public members
        
        #endregion

        #region Events
        private void CardList_Load(object sender, EventArgs e)
        {
            try
            {
                cboCardType.DataSource = Common.GetCardTypes(true);
                cboCardType.DisplayMember = "Name";
                cboCardType.ValueMember = "CardTypeID";
                cboStatus.DataSource = Common.CardStatus;
                btnSearch_Click(null, null);
            }
            catch (Exception ex)
            {
                 MessageBox.Show(ex.Message);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void dgResult_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            dgResult.DisplayLayout.Scrollbars = Infragistics.Win.UltraWinGrid.Scrollbars.Both;
            dgResult.DisplayLayout.Override.AllowRowFiltering = Infragistics.Win.DefaultableBoolean.True;
            dgResult.DisplayLayout.Bands[0].Columns["CardTypeID"].Hidden = true;            
            dgResult.DisplayLayout.Bands[0].Columns["CardID"].Header.Caption = "Mã thẻ";
            dgResult.DisplayLayout.Bands[0].Columns["CardID"].AutoSizeMode = Infragistics.Win.UltraWinGrid.ColumnAutoSizeMode.AllRowsInBand;
            dgResult.DisplayLayout.Bands[0].Columns["VIP"].Header.Caption = "Thẻ VIP";
            dgResult.DisplayLayout.Bands[0].Columns["VIP"].AutoSizeMode = Infragistics.Win.UltraWinGrid.ColumnAutoSizeMode.AllRowsInBand;
            dgResult.DisplayLayout.Bands[0].Columns["FromDate"].Header.Caption = "Ngày bắt đầu";
            dgResult.DisplayLayout.Bands[0].Columns["FromDate"].AutoSizeMode = Infragistics.Win.UltraWinGrid.ColumnAutoSizeMode.AllRowsInBand;
            dgResult.DisplayLayout.Bands[0].Columns["FromDate"].Format = "dd/MM/yyyy";
            dgResult.DisplayLayout.Bands[0].Columns["ToDate"].Header.Caption = "Ngày kết thúc";
            dgResult.DisplayLayout.Bands[0].Columns["ToDate"].AutoSizeMode = Infragistics.Win.UltraWinGrid.ColumnAutoSizeMode.AllRowsInBand;
            dgResult.DisplayLayout.Bands[0].Columns["ToDate"].Format = "dd/MM/yyyy";
            dgResult.DisplayLayout.Bands[0].Columns["Active"].Hidden = true;
            dgResult.DisplayLayout.Bands[0].Columns["Status"].Header.Caption = "Trạng thái";
            dgResult.DisplayLayout.Bands[0].Columns["Status"].AutoSizeMode = Infragistics.Win.UltraWinGrid.ColumnAutoSizeMode.AllRowsInBand;
            dgResult.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            dgResult.DisplayLayout.Override.ColumnAutoSizeMode = ColumnAutoSizeMode.VisibleRows;
            dgResult.DisplayLayout.Override.ColumnSizingArea = ColumnSizingArea.EntireColumn;
            dgResult.DisplayLayout.Override.AllowAddNew = AllowAddNew.No;
            dgResult.DisplayLayout.Override.AllowUpdate = Infragistics.Win.DefaultableBoolean.False;
            dgResult.DisplayLayout.Override.AllowDelete = Infragistics.Win.DefaultableBoolean.False;
            dgResult.DisplayLayout.Override.RowSelectors = Infragistics.Win.DefaultableBoolean.True;
            dgResult.DisplayLayout.Override.RowSelectorNumberStyle = RowSelectorNumberStyle.RowIndex;
            dgResult.DisplayLayout.Override.SelectTypeRow = SelectType.Single;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {            
            txtCardID.Text = txtCardID.Text.Trim();
            try
            {
                object cardTypeID, cardID, cardStatus;
                if (cboCardType.SelectedIndex<=0)
                {
                    cardTypeID = DBNull.Value;
                }
                else
                {
                    cardTypeID = cboCardType.Value;
                }

                cardID = Common.DBNullValue(txtCardID.Text);
                
                if (cboStatus.SelectedIndex<=0)
                {
                    cardStatus = DBNull.Value;
                }
                else
                {
                    cardStatus = (cboStatus.SelectedIndex == 2);
                }

                Search(cardTypeID, cardID, cardStatus);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Search(DBNull.Value, DBNull.Value, DBNull.Value);
                frmAddDeleteCard = new AddDeleteCard(true);
                frmAddDeleteCard.CardAddedRemoved += new AddDeleteCard.CardAddedRemovedHandler(frm_CardAddedRemoved);
                frmAddDeleteCard.Show();
            }
            catch
            {
               
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgResult.Selected.Rows.Count > 0)
            {
                try
                {
                    _selectedRow = dgResult.Selected.Rows[0];
                    EditCard frmEditCard = new EditCard(_selectedRow);
                    frmEditCard.UpdateCard += new EditCard.UpdateCardHandler(frmEditCard_UpdateCard);
                    frmEditCard.ShowDialog();
                }
                catch
                {
                }
            }
            
        }

        private void dgResult_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            e.Row.Selected = true;
            btnEdit_Click(null, null);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Search(DBNull.Value, DBNull.Value, DBNull.Value);
            frmAddDeleteCard = new AddDeleteCard(false);
            frmAddDeleteCard.CardAddedRemoved += new AddDeleteCard.CardAddedRemovedHandler(frm_CardAddedRemoved);
            frmAddDeleteCard.Show();
        }

        private void dgResult_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (dgResult.Selected.Rows.Count > 0)
                {
                    if (MessageBox.Show("Bạn chắc chắn muốn xóa thẻ đang chọn?",
                        this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DeleteCard(dgResult.Selected.Rows[0].Cells["CardID"].Value.ToString());
                    }                    
                }
            }            
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region Constructros
        public CardList()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        #endregion

        

        

       
        
    }
}
